"use client"
import React, {useEffect, useState} from "react";
import {
    Button,
    Col, Drawer,
    Form,
    Input,
    message,
    Modal,
    Row,
    Select,
    Space,
    Switch,
    Table,
    TableProps,
    Tooltip,
} from 'antd';
import {DeleteOutlined} from "@ant-design/icons";

import {definitionStatus, myTaskDelete, start, taskList} from "@/clientApi/flowable/myProcess/index";
import AddMyTaskView from "./component/addMyTaskView";
import FinishTaskDetailView from "@/components/ProcessDetail";
import useResponsiveLayout from "@/utils/useResponsiveLayout";
import { globalMessage } from "@/utils/message";
import RenderIconsCustom from "@/components/CustomIconSelector/conponents";
import { useConfirmModal } from "@/utils/ConfirmModal";

const MyProcessView: React.FC = () => {
        const { confirm } = useConfirmModal();
    const initialQueryParams = {
        pageNum: 1,
        pageSize: 10,
        name: undefined,

    };

    interface DataType {
    }

    const [form] = Form.useForm();
    const [record, setRecord] = useState<Record<string, any>>({});
    const [forceUpdateKey, setForceUpdateKey] = useState(0); // 用于强制更新组件的 key
    const [dataList, setDataList] = useState<DataType[]>([]);
    const [open, setOpen] = useState(false);
    const [procesOpen, setProcessOpen] = useState(false);//打开详情
    const [processDetail, setProcessDetail] = useState<Record<string, any>>({});
    const columns: TableProps<DataType>['columns'] = [
        {
            title: '任务编号',
            dataIndex: 'procInsId',
            key: 'procInsId',
            align: 'center'
        },
        {
            title: '流程名称',
            dataIndex: 'procDefName',
            key: 'procDefName',
            align: 'center'
        },
        {
            title: '任务节点',
            dataIndex: 'taskName',
            key: 'taskName',
            align: 'center'
        }, {
            title: '流程类别',
            dataIndex: 'category',
            key: 'category',
            align: 'center'
        }, {
            title: '版本',
            dataIndex: 'procDefVersion',
            key: 'procDefVersion',
            align: 'center'
        }, {
            title: '业务主键',
            dataIndex: 'businessKey',
            key: 'businessKey',
            align: 'center'
        }, {
            title: '提交时间',
            dataIndex: 'createTime',
            key: 'createTime',
        }, {
            title: '流程状态',
            dataIndex: 'suspensionState',
            key: 'suspensionState',
            align: 'center',
            render: (_, record:any) => (
                <div>{record.finishTime !== null ? '已完成' : '进行中'}</div>
            )
        }, {
            title: '耗时',
            dataIndex: 'duration',
            key: 'duration',
            align: 'center',

        }, {
            title: '当前节点',
            dataIndex: 'taskName',
            key: 'taskName',
            align: 'center',

        }, {
            title: '办理',
            dataIndex: 'assigneeName',
            key: 'assigneeName',
            align: 'center',
            render: (_, record:any) => (
                <div>{record.assigneeName}{record.deptName}</div>
            )

        }, {
            title: '操作',
            dataIndex: 'action',
            key: 'action',
            render: (_, record:any) => (
                <Space size="middle">
                    {record?.roleId !== 1 && (
                        <Tooltip title="详情">
                            <Button
                                type="link"
                                size="small"
                                icon={<RenderIconsCustom icon="edit"/>}
                                onClick={() => DetailClick(record)}/>
                        </Tooltip>

                    )}
                    {record?.roleId !== 1 && (
                        <Tooltip title="删除">
                            <Button
                                type="link"
                                size="small"
                                icon={<DeleteOutlined/>}
                                onClick={() => handleDelete(record)}/>
                        </Tooltip>
                    )}

                </Space>
            ),
        },
    ];
    const [queryParams, setQueryParams] = useState(initialQueryParams);
    const [total, setTotal] = useState(0);
    const [openDataPermissions, setOpenDataPermissions] = useState<boolean>(false);
    useEffect(() => {
        getList();
    }, [queryParams]);  // 监听 queryParams 变化，调用 getList

    /** 查询用户列表 */
    function getList() {
        taskList(queryParams).then((res:any) => {
            setDataList(res.rows.map((item: any) => ({
                ...item,
                key: item.taskId // 使用 userId 作为唯一的 key
            })))
            setTotal(res.total); // 更新 total，用于分页
        });
    }

    // 查询列表
    function handleSearch() {
        form.validateFields().then(values => {
            console.log(values, 'values')
            setQueryParams(prevQueryParams => ({
                ...queryParams,
                name: values.name,
            }));
        });
    }

    // 重置查询
    const resetSearch = () => {
        form.resetFields();
        setQueryParams(initialQueryParams); // 重置为初始状态
    }

    // 分页变化
    const handleTableChange = (page: number, pageSize: number) => {
        setQueryParams({
            ...queryParams,
            pageNum: page,
            pageSize: pageSize,
        });
    };
    // 查看详情按钮
    const DetailClick = (e: any) => {
        console.log("e", e)
        setProcessDetail(e)
        setProcessOpen(true);

    }
    /**
     * 新增
     * @param e
     * @constructor
     */
    const handleAddClick = () => {
        setOpen(true)

    }
    // 删除按钮
    const handleDelete = (e: any) => {
        const instanceId = e.procInsId;
        const deleteReason = null;
        confirm({
            title: '系统提示',
            content: (`是否确认删除用户编号为"${instanceId}"的数据项？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                myTaskDelete(instanceId, deleteReason).then((res: any) => {
                    if (res?.code === 200) {
                         globalMessage().info("删除成功")
                        getList()
                    }
                })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作

            },
        });

    }
    const onChangeStatus = (checked: boolean, event: any, value: any) => {
        console.log(checked, event, value);
        const text = value.suspensionState === "1" ? "启用" : "停用";
        confirm({
            title: '系统提示',
            content: (`确认要"${text}"+"${value.name}"流程吗？`),
            onOk() {
                // 用户点击“确定”按钮后执行的操作
                definitionStatus(value.id, checked === false ? "2" : "1").then((res:any) => {
                    if (res?.code === 200) {
                         globalMessage().info("修改成功").then(r => {
                        })
                        getList()
                    }
                })
                // 在这里可以添加删除记录的逻辑
            },
            onCancel() {
                // 用户点击“取消”按钮后执行的操作
                setForceUpdateKey(prevKey => prevKey + 1); // 更新 key 以强制重新渲染组件
            },
        });
        // console.log(checked,event,value,value.status == "0")
    }
    return (
        <div className='home'>
            <Row gutter={20} style={{paddingTop: "20px"}}>
                <Col span={24}>
                    <div><Form
                        form={form}
                        layout={useResponsiveLayout("inline")}
                        name="definition_form_controls"
                        style={{marginTop: 10, marginLeft: 10, marginBottom: 10}}>
                        <Form.Item
                            name="name"
                            label="流程名称">
                            <Input />
                        </Form.Item>
                        <Form.Item>
                            <Button type="primary" htmlType="submit" onClick={handleSearch} style={{
                            }}>
                                查询
                            </Button>
                            <Button type="primary" htmlType="reset" onClick={resetSearch}>
                                重置
                            </Button>
                        </Form.Item>
                    </Form></div>
                    <div><Button type="primary" ghost onClick={() => {
                        handleAddClick()
                    }} style={{margin: 10}}>
                        新增
                    </Button></div>
                    <Table<DataType> rowKey="taskId"
                     columns={columns}
                      dataSource={dataList}
                      scroll={{x:'max-content'}}
                       pagination={{
                        current: queryParams.pageNum,
                        pageSize: queryParams.pageSize,
                        total: total,
                        showSizeChanger: true, // 显示分页尺寸切换器
                        pageSizeOptions: ['10', '20', '50'], // 分页尺寸选项
                        onShowSizeChange: handleTableChange, // 分页尺寸变化时的回调
                        onChange: handleTableChange
                    }}/>
                </Col>
            </Row>
            <Modal title="新增流程" open={open} footer={null} onCancel={() => setOpen(false)}>
                <AddMyTaskView OnCanCle={()=>{ setOpen(false), getList()}} ></AddMyTaskView>
            </Modal>
            <Drawer
                title="流程详情"
                placement="right"
                closable={false}
                onClose={()=>{setProcessOpen(false)}}
                open={procesOpen}
                width={"50%"}
                key={"right"}
            >
                <FinishTaskDetailView  processDetail={processDetail} />
            </Drawer>
        </div>
    )
};
export default MyProcessView;
